import React, { useEffect, useState } from 'react';
import { Table, Tag, Button, Space, message, Modal, Form, Input, Select } from 'antd';
import { ISysUser } from '../types/sys_user';
import { UserOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';

/**
 * 用户列表组件
 * 
 * 展示系统用户信息，支持分页、搜索、新增、编辑和删除操作
 */
const UserList: React.FC = () => {
  // 状态定义
  const [users, setUsers] = useState<ISysUser[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [total, setTotal] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [editingUser, setEditingUser] = useState<ISysUser | null>(null);
  const [form] = Form.useForm();

  // 模拟从API获取数据
  const fetchUsers = async (page: number, size: number) => {
    setLoading(true);
    try {
      // 实际应用中应替换为真实的API调用
      // const response = await axios.get('/api/users', { params: { page, size } });
      // 模拟数据
      setTimeout(() => {
        const mockUsers: ISysUser[] = Array(10).fill(0).map((_, index) => ({
          user_id: 1000 + index + (page - 1) * size,
          user_name: `user${1000 + index + (page - 1) * size}`,
          nick_name: `用户${index + 1 + (page - 1) * size}`,
          email: `user${index + 1 + (page - 1) * size}@example.com`,
          phonenumber: `1358888${(10000 + index + (page - 1) * size).toString().slice(-4)}`,
          sex: index % 3 === 0 ? '0' : index % 3 === 1 ? '1' : '2',
          status: index % 5 === 0 ? '1' : '0',
          del_flag: '0',
          user_type: index % 3 === 0 ? '00' : index % 3 === 1 ? '1' : '2',
          create_time: new Date().toISOString(),
          avatar: '',
          password: '******',
          login_ip: '127.0.0.1',
          create_by: 'admin',
          update_by: 'admin',
          dept_id: 100 + (index % 5),
          work_unit: `公司${index % 5 + 1}`,
        }));
        
        setUsers(mockUsers);
        setTotal(100); // 模拟总数
        setLoading(false);
      }, 500);
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败，请稍后重试');
      setLoading(false);
    }
  };

  // 页面加载时获取数据
  useEffect(() => {
    fetchUsers(currentPage, pageSize);
  }, [currentPage, pageSize]);

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  // 打开编辑模态框
  const handleEdit = (user: ISysUser) => {
    setEditingUser(user);
    form.setFieldsValue(user);
    setModalVisible(true);
  };

  // 打开新增模态框
  const handleAdd = () => {
    setEditingUser(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 处理删除
  const handleDelete = (userId: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此用户吗？此操作不可恢复。',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        // 实际应用中应替换为真实的API调用
        // await axios.delete(`/api/users/${userId}`);
        message.success('用户删除成功');
        fetchUsers(currentPage, pageSize);
      }
    });
  };

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingUser) {
        // 更新用户
        // await axios.put(`/api/users/${editingUser.user_id}`, values);
        message.success('用户信息更新成功');
      } else {
        // 新增用户
        // await axios.post('/api/users', values);
        message.success('用户添加成功');
      }
      
      setModalVisible(false);
      fetchUsers(currentPage, pageSize);
    } catch (error) {
      console.error('表单提交失败:', error);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'user_id',
      key: 'user_id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'user_name',
      key: 'user_name',
    },
    {
      title: '昵称',
      dataIndex: 'nick_name',
      key: 'nick_name',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '手机号',
      dataIndex: 'phonenumber',
      key: 'phonenumber',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: (sex: string) => {
        let text = '未知';
        let color = 'default';
        
        if (sex === '0') {
          text = '男';
          color = 'blue';
        } else if (sex === '1') {
          text = '女';
          color = 'pink';
        }
        
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        return status === '0' ? 
          <Tag color="green">正常</Tag> : 
          <Tag color="red">停用</Tag>;
      }
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: ISysUser) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDelete(record.user_id as number)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="user-list-container">
      <div className="table-operations" style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={handleAdd}
        >
          新增用户
        </Button>
      </div>
      
      <Table
        columns={columns}
        dataSource={users}
        rowKey="user_id"
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`
        }}
        loading={loading}
        onChange={handleTableChange}
      />

      {/* 新增/编辑用户模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          name="userForm"
          initialValues={editingUser || {}}
        >
          <Form.Item
            name="user_name"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
          </Form.Item>
          
          <Form.Item
            name="nick_name"
            label="昵称"
            rules={[{ required: true, message: '请输入昵称' }]}
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>
          
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>
          
          <Form.Item
            name="phonenumber"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1\d{10}$/, message: '请输入有效的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          
          <Form.Item
            name="sex"
            label="性别"
          >
            <Select>
              <Select.Option value="0">男</Select.Option>
              <Select.Option value="1">女</Select.Option>
              <Select.Option value="2">未知</Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Select.Option value="0">正常</Select.Option>
              <Select.Option value="1">停用</Select.Option>
            </Select>
          </Form.Item>
          
          {!editingUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码长度不能少于6位' }
              ]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}
          
          <Form.Item
            name="work_unit"
            label="工作单位"
          >
            <Input placeholder="请输入工作单位" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserList; 